import oss2
from app.config import settings
import logging

logger = logging.getLogger(__name__)


def get_oss_auth():
    """获取OSS认证"""
    return oss2.Auth(
        settings.OSS_ACCESS_KEY_ID,
        settings.OSS_ACCESS_KEY_SECRET
    )


def get_oss_bucket(bucket_name=None):
    """获取OSS Bucket"""
    auth = get_oss_auth()
    bucket = oss2.Bucket(
        auth,
        settings.OSS_ENDPOINT,
        bucket_name or settings.OSS_BUCKET_NAME
    )
    return bucket


def upload_to_oss(file_path, object_name, bucket_name=None):
    """
    上传文件到OSS

    参数:
    - file_path: 本地文件路径
    - object_name: OSS对象名称
    - bucket_name: OSS桶名称(可选)

    返回:
    - 文件公开URL
    """
    try:
        bucket = get_oss_bucket(bucket_name)

        # 上传文件
        result = bucket.put_object_from_file(object_name, file_path)

        if result.status == 200:
            # 生成公开URL
            if settings.OSS_USE_HTTPS:
                protocol = "https"
            else:
                protocol = "http"

            url = f"{protocol}://{bucket.bucket_name}.{settings.OSS_ENDPOINT}/{object_name}"
            logger.info(f"文件上传成功: {url}")
            return url
        else:
            raise Exception(f"OSS上传失败: {result.status}")

    except Exception as e:
        logger.error(f"OSS上传出错: {str(e)}")
        raise